<template>
    <div class="industry-management">
        <!-- 头部操作区域 -->
        <div class="header">
            <h2>行业管理</h2>
            <div class="operations">
                <el-button type="primary" @click="showAddDialog">+ 新建</el-button>
                <el-button :icon="Refresh" @click="refreshData" />
                <el-dropdown trigger="click" @command="handleDensity">
                    <el-button :icon="Operation" />
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="default" :class="{active: density === 'default'}">默认</el-dropdown-item>
                            <el-dropdown-item command="medium" :class="{active: density === 'medium'}">中等</el-dropdown-item>
                            <el-dropdown-item command="small" :class="{active: density === 'small'}">紧凑</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-popover placement="bottom" width="160">
                    <template #reference>
                        <el-button :icon="Setting" />
                    </template>
                    <div class="column-settings">
                        <div class="setting-header">
                            <span>列展示</span>
                            <el-button type="text" @click="resetColumns">重置</el-button>
                        </div>
                        <el-checkbox-group v-model="visibleColumns">
                            <el-checkbox
                                v-for="col in columns"
                                :key="col.prop"
                                :label="col.prop"
                            >{{ col.label }}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-popover>
            </div>
        </div>

        <!-- 数据表格 -->
        <el-table
            :data="tableData"
            :size="density"
            style="width: 100%"
            empty-text="暂无数据"
            row-key="name"
            :tree-props="{ children: 'children' }"
        >
            <el-table-column
                v-if="visibleColumns.includes('index')"
                prop="index"
                label="序号"
                width="80"
            >
                <template #default="{ row }">
                    <span v-if="!row.parent">{{ row.index }}</span>
                </template>
            </el-table-column>
            <el-table-column
                v-if="visibleColumns.includes('name')"
                prop="name"
                label="名称"
            />
            <el-table-column
                v-if="visibleColumns.includes('editTime')"
                prop="editTime"
                label="编辑时间"
                width="180"
            />
            <el-table-column label="操作" width="220">
                <template #default="{ row }">
                    <el-button
                        v-if="getLevel(row) <= 2"
                        type="text"
                        @click="addSubCategory(row)"
                    >新增子类</el-button>
                    <el-button type="text" @click="editItem(row)">编辑</el-button>
                    <el-button
                        v-if="!row.children"
                        type="text"
                        @click="deleteItem(row)"
                        style="color: var(--el-color-danger)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination
                background
                layout="total, prev, pager, next"
                :total="total"
                :page-size="pageSize"
            />
        </div>

        <!-- 添加行业对话框 -->
        <el-dialog
            v-model="dialogVisible"
            :title="isEditing ? '编辑' : (isAddingSubCategory ? '新增子组件' : '添加行业')"
            width="500px"
        >
            <el-form :model="form" :rules="rules" ref="formRef">
                <el-form-item label="行业名称" prop="name" required>
                    <el-input
                        v-model="form.name"
                        placeholder="请输入行业名称"
                        clearable
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmSubmit">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Refresh, Operation, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 表格数据
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const density = ref('default')
const visibleColumns = ref(['index', 'name', 'editTime'])
const columns = reactive([
    { prop: 'index', label: '序号' },
    { prop: 'name', label: '名称' },
    { prop: 'editTime', label: '编辑时间' }
])

// 对话框相关
const dialogVisible = ref(false)
const isEditing = ref(false)
const isAddingSubCategory = ref(false)
const form = reactive({ name: '' })
const formRef = ref(null)
const rules = {
    name: [{ required: true, message: '请输入行业名称', trigger: 'blur' }]
}

let editingRow = null

const getLevel = (row) => {
    let level = 1
    let current = row
    while (current && current.parentRow) {
        level++
        current = current.parentRow
    }
    return level
}

// 操作方法
const showAddDialog = () => {
    isEditing.value = false
    isAddingSubCategory.value = false
    form.name = ''
    dialogVisible.value = true
    editingRow = null
}

const addSubCategory = (row) => {
    if (!row.children) row.children = []
    if (row.children.length >= 2) {
        editItem(row)
        return
    }
    isEditing.value = false
    isAddingSubCategory.value = true
    form.name = ''
    dialogVisible.value = true
    editingRow = row
}

const editItem = (row) => {
    isEditing.value = true
    isAddingSubCategory.value = false
    form.name = row.name
    dialogVisible.value = true
    editingRow = row
}

const deleteItem = (row) => {
    const index = tableData.value.indexOf(row)
    if (index !== -1) {
        tableData.value.splice(index, 1)
        // 重新设置序号
        tableData.value.forEach((item, i) => {
            item.index = i + 1
        })
    }
}

const confirmSubmit = async () => {
    await formRef.value.validate()

    if (isEditing.value && editingRow) {
        editingRow.name = form.name
        editingRow.editTime = new Date().toLocaleString()
    } else if (isAddingSubCategory.value && editingRow) {
        if (!editingRow.children) editingRow.children = []
        editingRow.children.push({
            name: form.name,
            parent: true,
            parentRow: editingRow,
            editTime: new Date().toLocaleString()
        })
    } else {
        tableData.value.push({
            index: tableData.value.length + 1,
            name: form.name,
            editTime: new Date().toLocaleString()
        })
    }

    dialogVisible.value = false
    isEditing.value = false
    isAddingSubCategory.value = false
    editingRow = null
}

const refreshData = () => {
    ElMessage.success('刷新成功')
    // 添加一个小延迟模拟
    const oldData = [...tableData.value]
    tableData.value = []
    setTimeout(() => {
        tableData.value = oldData
    }, 300)
}

const handleDensity = (command) => {
    density.value = command
}

const resetColumns = () => {
    visibleColumns.value = ['index', 'name', 'editTime']
}

// 初始化加载数据
onMounted(() => {
    // 这里可以添加初始化数据加载逻辑
})
</script>

<style scoped>
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.operations {
    display: flex;
    gap: 10px;
}

.column-settings {
    padding: 10px;
}

.setting-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
}

.active {
    background-color: #f5f7fa;
}
</style>